<script lang="ts" setup>
import type { Dayjs } from 'dayjs';

import type { InventorySummaryParams } from '#/api/inventory/inventory';
import type { Warehouse } from '#/models/inventory/inventory';

import { onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';

import {
  Button,
  Card,
  Col,
  DatePicker,
  message,
  Row,
  Select,
  Statistic,
} from 'ant-design-vue';

import {
  getInventorySummary,
} from '#/api/inventory/inventory';
import { getWarehouseList } from '#/api/inventory/warehouse';

// 国际化
const { t } = useI18n();

const loading = ref(false);
const dateRange = ref<[Dayjs, Dayjs] | null>(null);
const warehouseId = ref<string>('');
const warehouseOptions = ref<{ label: string; value: string }[]>([]);

// 库存概览数据
const totalQuantity = ref(0);
const totalValue = ref(0);
const inQuantity = ref(0);
const outQuantity = ref(0);
const turnoverRate = ref(0);

// 趋势图数据
type TrendDataType = { date: string; quantity: number; value: number };
type CategoryDataType = { name: string; value: number };
type WarehouseDataType = { name: string; value: number };

type InventorySummaryResult = {
  category_data?: CategoryDataType[];
  in_quantity: number;
  out_quantity: number;
  total_quantity: number;
  total_value: number;
  trend_data?: TrendDataType[];
  turnover_rate: number;
  warehouse_data?: WarehouseDataType[];
};

const trendData = ref<TrendDataType[]>([]);
const categoryData = ref<CategoryDataType[]>([]);
const warehouseData = ref<WarehouseDataType[]>([]);

/**
 * 加载仓库数据
 * @returns Promise<void>
 */
async function loadWarehouseData() {
  try {
    const response = await getWarehouseList({ page_size: 999 });
    warehouseOptions.value =
      response.items.map((warehouse: Warehouse) => ({
        value: warehouse.warehouse_id.toString(),
        label: warehouse.warehouse_name,
      })) || [];
  } catch (error) {
    message.error(t('inventory.summary.loadWarehouseFailed'));
  }
}

/**
 * 获取库存汇总数据
 * @returns Promise<void>
 */
async function getInventorySummary() {
  try {
    loading.value = true;

    // 构建查询参数
    const params: InventorySummaryParams = {};

    if (dateRange.value && dateRange.value.length === 2) {
      params.start_date = dateRange.value[0].format('YYYY-MM-DD');
      params.end_date = dateRange.value[1].format('YYYY-MM-DD');
    }

    if (warehouseId.value) {
      params.warehouse_id = warehouseId.value;
    }

    // 调用真实API获取库存汇总数据
    let result: InventorySummaryResult;
    try {
      // 调用真实API获取库存汇总数据
      const response = await getInventorySummary(params);
      result = response;
    } catch (apiError) {
      // API调用失败时使用模拟数据
      message.warn(t('inventory.summary.useMockData'));
      result = {
        total_quantity: 12500,
        total_value: 875600.5,
        in_quantity: 3200,
        out_quantity: 2800,
        turnover_rate: 65.3,
        trend_data: [
          { date: '01/01', quantity: 10000, value: 700000 },
          { date: '01/02', quantity: 10500, value: 720000 },
          { date: '01/03', quantity: 11000, value: 735000 },
          { date: '01/04', quantity: 11500, value: 750000 },
          { date: '01/05', quantity: 12000, value: 775000 },
          { date: '01/06', quantity: 12500, value: 800000 },
          { date: '01/07', quantity: 12500, value: 875600.5 },
        ],
        category_data: [
          { name: '原材料', value: 5000 },
          { name: '半成品', value: 3000 },
          { name: '成品', value: 4000 },
          { name: '辅料', value: 500 },
        ],
        warehouse_data: [
          { name: '主仓库', value: 8000 },
          { name: '成品仓库', value: 3000 },
          { name: '原材料仓库', value: 1500 },
        ],
      };
    }

    // 更新概览数据
    totalQuantity.value = result.total_quantity || 0;
    totalValue.value = result.total_value || 0;
    inQuantity.value = result.in_quantity || 0;
    outQuantity.value = result.out_quantity || 0;
    turnoverRate.value = result.turnover_rate || 0;

    // 更新图表数据
    trendData.value = result.trend_data || [];
    categoryData.value = result.category_data || [];
    warehouseData.value = result.warehouse_data || [];

    // 渲染图表
    renderCharts();
  } catch (error) {
    message.error(t('inventory.summary.loadSummaryFailed'));
  } finally {
    loading.value = false;
  }
}

/**
 * 重置筛选条件
 * @returns void
 */
function onReset() {
  dateRange.value = null;
  warehouseId.value = '';
  getInventorySummary();
}

/**
 * 搜索按钮回调
 * @returns void
 */
function onSearch() {
  getInventorySummary();
}

/**
 * 渲染图表
 * 注意：图表功能将在图表组件可用后实现
 * @returns void
 */
function renderCharts() {
  // 图表渲染逻辑将在图表组件可用后实现
  console.log('Chart data loaded:', { trendData, categoryData, warehouseData });
}

// 初始化
onMounted(() => {
  loadWarehouseData();
  getInventorySummary();
});
</script>

<template>
  <div class="inventory-summary-container p-5">
    <div class="mb-6">
      <h1 class="mb-2 text-2xl font-bold">
        {{ t('inventory.summary.title') }}
      </h1>
      <p class="text-gray-500">{{ t('inventory.summary.description') }}</p>
    </div>

    <!-- 筛选条件 -->
    <Card class="mb-6">
      <Row :gutter="16">
        <Col span="{8}">
          <DatePicker.RangePicker v-model="dateRange" class-name="w-full" />
        </Col>
        <Col span="{8}">
          <Select
            v-model="warehouseId"
            placeholder="请选择仓库"
            allow-clear
            class-name="w-full"
          >
            <Select.Option
              v-for="item in warehouseOptions"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </Select.Option>
          </Select>
        </Col>
        <Col span="{8}">
          <Row :gutter="16">
            <Col span="{12}">
              <Button type="primary" @click="onSearch" :loading="loading">
                {{ t('common.search') }}
              </Button>
            </Col>
            <Col span="{12}">
              <Button @click="onReset">
                {{ t('common.reset') }}
              </Button>
            </Col>
          </Row>
        </Col>
      </Row>
    </Card>

    <!-- 统计卡片 -->
    <Row :gutter="16" class-name="mb-6">
      <Col span="{6}">
        <Card>
          <Statistic
            title="{t('inventory.summary.totalQuantity')}"
            :value="totalQuantity"
            suffix="件"
            :precision="0"
          />
        </Card>
      </Col>
      <Col span="{6}">
        <Card>
          <Statistic
            title="{t('inventory.summary.totalValue')}"
            :value="totalValue"
            suffix="元"
            :precision="2"
          />
        </Card>
      </Col>
      <Col span="{6}">
        <Card>
          <Statistic
            title="{t('inventory.summary.inQuantity')}"
            :value="inQuantity"
            suffix="件"
            :precision="0"
          />
        </Card>
      </Col>
      <Col span="{6}">
        <Card>
          <Statistic
            title="{t('inventory.summary.outQuantity')}"
            :value="outQuantity"
            suffix="件"
            :precision="0"
          />
        </Card>
      </Col>
    </Row>

    <Row :gutter="16" class-name="mb-6">
      <Col span="{24}">
        <Card
          title="{t('inventory.summary.turnoverRate')}"
          class-name="text-center"
        >
          <Statistic :value="turnoverRate" suffix="%" :precision="2" />
        </Card>
      </Col>
    </Row>

    <!-- 趋势图 -->
    <Row :gutter="16" class-name="mb-6">
      <Col span="{24}">
        <Card title="{t('inventory.summary.trend')}">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 300px;
              background-color: #f5f5f5;
            "
          >
            {{ t('inventory.summary.chartArea') }}
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 分类统计 -->
    <Row :gutter="16">
      <Col span="{12}">
        <Card title="{t('inventory.summary.category')}">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 300px;
              background-color: #f5f5f5;
            "
          >
            {{ t('inventory.summary.categoryChartArea') }}
          </div>
        </Card>
      </Col>
      <Col span="{12}">
        <Card title="{t('inventory.summary.warehouseDistribution')}">
          <div
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              width: 100%;
              height: 300px;
              background-color: #f5f5f5;
            "
          >
            {{ t('inventory.summary.warehouseChartArea') }}
          </div>
        </Card>
      </Col>
    </Row>
  </div>
</template>

<style lang="less" scoped>
.inventory-summary-container {
  &-p-5 {
    padding: 20px;
  }
}

// 可以根据需要添加更多样式
</style>
